package com.freesky.biz.pay.service;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 中石化森美发券服务
 */
@Service
public class SinopecService {

    private static Logger logger = LoggerFactory.getLogger(SinopecService.class);

    private static final String APP_ID = "1744253736";
    private static final String API_KEY = "96b68442920c7e9855cc14f03dfc6a49";
    private static final String PREFIX_URL = "https://e.o2obest.cn";
    /**
     * 请求发券接口
     * @param outSn：外部流水号，联营单位内唯一。长度32以内
     * @param activityCode：联营活动编码
     * @param phone：md5模式：11位手机号
     * @return
     */
    public AjaxResult sendCrmPackage(String outSn,String activityCode,String phone){
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("requestTime",String.valueOf(System.currentTimeMillis()/1000));
            paramMap.put("activityCode",activityCode);
            paramMap.put("app",APP_ID);
            paramMap.put("outSn",outSn);
            paramMap.put("phone", phone);
            paramMap.put("askPieces", "1");
            paramMap.put("type", "md5");
            String signMsg = DigestUtils.md5Hex(sign(paramMap));
            paramMap.put("sign",signMsg);

            //{"code":200,"msg":"\u6210\u529f\u8bf7\u6c42\u53d1\u5238","data":{"activityCode":"CPA202470728","outSn":"1909872881119137792","ticketNo":"TN2025040915355355069680"}}
            logger.info("sendCrmPackage req:"+ JSON.toJSONString(paramMap));
            String result = HttpRequest.post(PREFIX_URL +"/api/crmPackage/send")
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE,"multipart/form-data")
                    .charset("utf-8")
                    .form("requestTime",paramMap.get("requestTime"))
                    .form("phone",phone)
                    .form("activityCode",paramMap.get("activityCode"))
                    .form("outSn",paramMap.get("outSn"))
                    .form("askPieces",paramMap.get("askPieces"))
                    .form("type",paramMap.get("type"))
                    .form("sign",paramMap.get("sign"))
                    .timeout(10000)
                    .execute().body();
            logger.info("sendCrmPackage resp:"+ result);
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("code");
            String message = new String(jsonObject.getString("msg").getBytes("utf-8"));
            logger.info("sendCrmPackage message :"+ message);
            if(jsonObject.getIntValue("code")==200){
                return AjaxResult.success(message,jsonObject.getJSONObject("data").getString("ticketNo"));
            } else {
                return AjaxResult.error(message);
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作失败，系统异常!");
        }
    }

    /**
     * 2.2、查询发券状态
     * @param activityCode:活动编码
     * @param outSn
     * @param ticketNo
     * @return
     */
    public AjaxResult queryCrmPackage(String activityCode,String outSn,String ticketNo){
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("app",APP_ID);
            paramMap.put("requestTime",String.valueOf(System.currentTimeMillis()/1000));
            paramMap.put("activityCode",activityCode);
            if(StringUtils.isNotBlank(ticketNo)){
                paramMap.put("ticketNo",ticketNo);
            }
            if(StringUtils.isNotBlank(outSn)){
                paramMap.put("outSn",outSn);
            }
            paramMap.put("type", "md5");
            String signMsg = DigestUtils.md5Hex(sign(paramMap));
            paramMap.put("sign",signMsg);

            //{"code":200,"msg":"\u5df2\u53d1\u5238","data":{"pushStatus":2,"pushTime":"2025-04-09 15:36:14","ticketNo":"TN2025040915355355069680","pipelineCode":"CB17441841539863833956"}}
            logger.info("queryCrmPackage req:"+ JSON.toJSONString(paramMap));
            HttpRequest httpRequest = HttpRequest.post(PREFIX_URL +"/api/crmPackage/query")
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE,"multipart/form-data")
                    .charset("utf8")
                    .form("requestTime",paramMap.get("requestTime"))
                    .form("activityCode",paramMap.get("activityCode"))
                    .form("type",paramMap.get("type"))
                    .form("sign",paramMap.get("sign"));
            if(StringUtils.isNotEmpty(outSn)){
                httpRequest.form("outSn",outSn);
            }
            if(StringUtils.isNotEmpty(ticketNo)){
                httpRequest.form("ticketNo",ticketNo);
            }
            String result = httpRequest.timeout(10000).execute().body();

            logger.info("queryCrmPackage resp:"+ result);
            JSONObject jsonObject = JSON.parseObject(result);
            String message = new String(jsonObject.getString("msg").getBytes("utf-8"));
            logger.info("queryCrmPackage message :"+ message);
            if(jsonObject.getIntValue("code")==200){
                return AjaxResult.success(message,jsonObject.getJSONObject("data"));
            } else {
                return AjaxResult.error(message);
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作失败，系统异常!");
        }
    }

    /**
     * 送券流水识别号查询送券情况接口
     * @param activityCode
     * @param pipelineCode :送券流水识别号查询送券情况接口
     * @param phone
     * @return
     */
    public AjaxResult querySendVoucherBill(String activityCode,
                                           String outSn,
                                           String pipelineCode,
                                           String phone){
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("app",APP_ID);
            paramMap.put("requestTime",String.valueOf(System.currentTimeMillis()/1000));
            paramMap.put("activityCode",activityCode);
            paramMap.put("pipelineCode",pipelineCode);
            paramMap.put("outSn",outSn);
            paramMap.put("phone", phone);
            paramMap.put("type", "md5");
            String signMsg = DigestUtils.md5Hex(sign(paramMap));
            paramMap.put("sign",signMsg);

            //{"code":200,"msg":"\u6210\u529f\u8bf7\u6c42","data":{"errorMsg":"\u6210\u529f","pipelineCode":"CB17441841539863833956","returnResult":"01","sendFlag":"1","voucherList":[{"voucherRuleName":"\u798f\u5efaC36\u6e20\u9053\u5238","voucherRuleCode":"$01-VC-17249176252981","voucherType":"C01","provinceCode":"100000","voucherStartTime":"20250409","cashValue":200,"endNumber":"0","voucherEndTime":"20250419","ruleDetail":"<font face=\"Arial, Verdana\"><span style=\"font-size: 13.3333px;\">\u798f\u5efaC36\u6e20\u9053\u5238<\/span><\/font>","useChannel":"C36","voucherStatus":"WY","marketCode":"20240829153523095","voucherCode":"10N504095242BuN04w","fullType":""},{"voucherRuleName":"\u798f\u5efaC12\u6e20\u9053","voucherRuleCode":"$01-VC-17249175444521","voucherType":"C01","provinceCode":"100000","voucherStartTime":"20250409","cashValue":500,"endNumber":"0","voucherEndTime":"20250419","ruleDetail":"<font face=\"Arial, Verdana\"><span style=\"font-size: 13.3333px;\">\u798f\u5efaC12\u6e20\u9053<\/span><\/font>","useChannel":"C05,C12","voucherStatus":"WY","marketCode":"20240829153523095","voucherCode":"10N50409QfdlK5AFk6","fullType":""}]}}
            logger.info("querySendVoucherBill req:"+ JSON.toJSONString(paramMap));
            String result = HttpRequest.post(PREFIX_URL +"/api/crmPackage/querySendVoucherBill")
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE,"multipart/form-data")
                    .charset("utf8")
                    .form("requestTime",paramMap.get("requestTime"))
                    .form("activityCode",paramMap.get("activityCode"))
                    .form("pipelineCode",paramMap.get("pipelineCode"))
                    .form("outSn",paramMap.get("outSn"))
                    .form("phone",paramMap.get("phone"))
                    .form("type",paramMap.get("type"))
                    .form("sign",paramMap.get("sign"))
                    .timeout(10000)
                    .execute().body();
            logger.info("querySendVoucherBill resp:"+ result);
            JSONObject jsonObject = JSON.parseObject(result);
            String message = new String(jsonObject.getString("msg").getBytes("utf-8"));
            logger.info("querySendVoucherBill message :"+ message);
            if(jsonObject.getIntValue("code")==200){
                return AjaxResult.success(message,jsonObject.getJSONObject("data"));
            } else {
                return AjaxResult.error(message);
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作失败，系统异常!");
        }
    }


    /**
     * 电子券作废券接口（可根据查询流水号返回券码进行作废券）
     * @param activityCode
     * @param voucherCode
     * @return
     */
    public AjaxResult crmPackageVoucherVoid(String activityCode,
                                            String outSn,
                                            String voucherCode){
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("app",APP_ID);
            paramMap.put("requestTime",String.valueOf(System.currentTimeMillis()/1000));
            paramMap.put("activityCode",activityCode);
            paramMap.put("voucherCode",voucherCode);
            paramMap.put("outSn",outSn);
            paramMap.put("type", "md5");
            String signMsg = DigestUtils.md5Hex(sign(paramMap));
            paramMap.put("sign",signMsg);

            logger.info("crmPackageVoucherVoid req:"+ JSON.toJSONString(paramMap));
            String result = HttpRequest.post(PREFIX_URL +"/api/crmPackage/crmPackageVoucherVoid")
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE,"multipart/form-data")
                    .charset("utf8")
                    .form("requestTime",paramMap.get("requestTime"))
                    .form("activityCode",paramMap.get("activityCode"))
                    .form("voucherCode",paramMap.get("voucherCode"))
                    .form("outSn",paramMap.get("outSn"))
                    .form("type",paramMap.get("type"))
                    .form("sign",paramMap.get("sign"))
                    .timeout(10000)
                    .execute().body();
            logger.info("crmPackageVoucherVoid resp:"+ result);

            JSONObject jsonObject = JSON.parseObject(result);
            String message = new String(jsonObject.getString("msg").getBytes("utf-8"));
            logger.info("crmPackageVoucherVoid message :"+ message);
            if(jsonObject.getIntValue("code")==200){
                return AjaxResult.success(message,jsonObject.getJSONObject("data"));
            } else {
                return AjaxResult.error(message);
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作失败，系统异常!");
        }
    }


    /**
     * 查询核销报告文件接口:建议次日8点后请求
     * @param day : 核销日期
     * @return
     */
    public AjaxResult crmPackageReport(String day){
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("app",APP_ID);
            paramMap.put("requestTime",String.valueOf(System.currentTimeMillis()/1000));
            paramMap.put("day",day);
            paramMap.put("type", "md5");
            String signMsg = DigestUtils.md5Hex(sign(paramMap));
            paramMap.put("sign",signMsg);

            logger.info("crmPackageReport req:"+ JSON.toJSONString(paramMap));
            String result = HttpRequest.get(PREFIX_URL +"/api/crmPackage/report")
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE,"multipart/form-data")
                    .charset("utf8")
                    .form("app",APP_ID)
                    .form("requestTime",paramMap.get("requestTime"))
                    .form("day",paramMap.get("day"))
                    .form("type",paramMap.get("type"))
                    .form("sign",paramMap.get("sign"))
                    .timeout(10000)
                    .execute().body();
            logger.info("crmPackageReport resp:"+ result);

            JSONObject jsonObject = JSON.parseObject(result);
            String message = new String(jsonObject.getString("msg").getBytes("utf-8"));
            logger.info("crmPackageReport message :"+ message);
            if(jsonObject.getIntValue("code")==200){
                return AjaxResult.success(message,jsonObject.getJSONObject("data"));
            } else {
                return AjaxResult.error(message);
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作失败，系统异常!");
        }
    }


    public String sign(Map<String, Object> params) {
        SortedMap<String, Object> sortedParamMap = new TreeMap<String, Object>(params);
        StringBuffer buffer = new StringBuffer();
        Iterator<Map.Entry<String, Object>> iter = sortedParamMap.entrySet()
                .iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Object> kvpair = iter.next();
            buffer.append(kvpair.getKey());
            buffer.append("=");
            buffer.append(kvpair.getValue().toString());
            if (iter.hasNext()) {
                buffer.append("&");
            }
        }
        String postParams = buffer.toString();
        postParams = postParams + "&key=" + API_KEY;
        return postParams;
    }
}
